package com.tarena.lbs.attach.service.impl;

import com.tarena.lbs.attach.pojo.vo.FileVO;
import com.tarena.lbs.attach.service.AttachService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Service
@Slf4j
public class AttachServiceImpl implements AttachService {
    
    // 从配置文件中读取存储路径
    @Value("${image_path}")
    private String uploadPath;
    
    // 从配置文件中读取访问前缀
    @Value("${url}")
    private String accessPrefix;
    
    @Override
    public FileVO uploadFile(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new Exception("上传文件不能为空");
        }
        
        // 创建存储目录
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        
        // 保存文件
        File dest = new File(uploadPath + fileName);
        file.transferTo(dest);
        
        // 构建返回对象
        FileVO fileVO = new FileVO();
        fileVO.setFileUuid(fileName);
        fileVO.setUrl(accessPrefix + fileName); // 设置可访问的URL
        
        log.info("文件上传成功: {}", fileVO.getUrl());
        return fileVO;
    }
}